package org.stvd.core.util;

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

@SuppressWarnings("unchecked")
public class SimpleDateFormatEx {

    private final String dataFormatStr;
    @SuppressWarnings("rawtypes")
    private final ThreadLocal threadLocal = new ThreadLocal();

    public SimpleDateFormatEx(String formatStr) {
        dataFormatStr = formatStr;
    }

    public DateFormat getDateFormat() {
        DateFormat df = (DateFormat) threadLocal.get();
        if (df == null) {
            df = new SimpleDateFormat(dataFormatStr);
            threadLocal.set(df);
        }
        return df;
    }

    public Date parse(String textDate) throws ParseException {
        return getDateFormat().parse(textDate);
    }

    public String format(Date d) {
        return getDateFormat().format(d);
    }

    public String format(Object d) {
        return getDateFormat().format(d);
    }

    public StringBuffer format(Date d, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        return getDateFormat().format(d, toAppendTo, fieldPosition);
    }

    public StringBuffer format(Object d, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        return getDateFormat().format(d, toAppendTo, fieldPosition);
    }

    public void setTimeZone(TimeZone zone) {
        getDateFormat().setTimeZone(zone);
    }
}
